package akbderby.page;

import java.util.List;

import org.slim3.datastore.Datastore;

import scenic3.ScenicPage;
import akbderby.GUtil;
import akbderby.model.Blobstore;
import akbderby.model.UserData;
import akbderby.service.UserDataService;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public abstract class BasePage extends ScenicPage {

    protected boolean isNull(Object o) {
        if (o == null)
            return true;
        if (o instanceof String && "".equals(o))
            return true;
        return false;
    }

    protected boolean isEmpty(List l) {
        if (l == null)
            return true;
        if (l.isEmpty())
            return true;
        return false;
    }

    protected UserData GUser() {
        UserData user = sessionScope("userData");
        if (GUtil.isNull(user)) {
            user = new UserData();
            sessionScope("userData", user);
        }
        return user;
    }

    protected UserData getUser() {

        UserData userData = sessionScope("userData");
        if (isNull(userData) || !userData.isAuthentication()) {

            UserService userService = UserServiceFactory.getUserService();
            User user = userService.getCurrentUser();
            if (!isNull(user)) {
                UserDataService us = new UserDataService();
                userData = us.getUser(user.getUserId());
                if (isNull(userData)) {
                    userData = new UserData();
                }
                userData.setUserId(user.getUserId());
                userData.setEmail(user.getEmail());
                userData.setNickName(user.getNickname());
                userData.setAuthentication(true);

                if (!isNull(userData.getGirlFriendId())) {
                    Key key =
                        KeyFactory.stringToKey(userData.getGirlFriendId());
                    Blobstore blobstore = Datastore.get(Blobstore.class, key);
                    sessionScope("girlfriend", blobstore);
                }

            } else {
                userData = new UserData();
            }
            sessionScope("userData", userData);
        }
        return userData;
    }

}
